package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellComments;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password =DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmp(EmployeeDTO dto) {
        //1.补充属性
        Employee employee =new Employee();
        BeanUtils.copyProperties(dto,employee);
        employee.setPassword(DigestUtils.md5DigestAsHex
                (PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //TODO:
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        //2.添加到数据库中
        employeeMapper.insert(employee);

    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO dto) {
        //1.分页查询用PageHelpe
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2.模糊查询name调用mapper
    Page<Employee> page = employeeMapper.list(dto.getName());
        log.info("根据姓名模糊分页查询的后的结果 {}",page);
        //3.封装到PageResult对象

        return new PageResult(page.getTotal(),page.getResult()) ;
    }

    /**
     * 员工状态修改
     * @param status
     * @param id
     */
    @Override
    public void enbaleOrDisable(Integer status, Long id) {
        Employee employee=Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据Id查数据
     * @param id
     * @return
     */
    @Override
    public Employee GetById(Long id){
        return  employeeMapper.GetById(id);
    }

    /**
     * 修改员工信息
     * @param dto
     */
    @Override
    public void Update(EmployeeDTO dto) {
        //1.复制数据给Employ表
        //2.Udate到数据库中
        Employee employee =new Employee();
        BeanUtils.copyProperties(dto,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public void UpdatePassword(PasswordEditDTO passDto) {

        //根据empId查询员工信息
        Employee employee = employeeMapper.getByempId(passDto.getEmpId());
        log.info("根据empId查询到员工信息{}",employee);
        //进行密码加密
     String   newPassword =DigestUtils.md5DigestAsHex(passDto.getNewPassword().getBytes());
     String   oldPassword =DigestUtils.md5DigestAsHex(passDto.getOldPassword().getBytes());
     if(oldPassword.equals(newPassword)){
         throw new AccountNotFoundException(MessageConstant.PASSWORD_EDIT_NEWANDOILD);
     }
     if(!oldPassword.equals(employee.getPassword())){
         throw new AccountNotFoundException(MessageConstant.PASSWORD_NEWERROR);
     }
        Employee emp =new Employee();
       emp.setId(BaseContext.getCurrentId());
       emp.setUpdateUser(BaseContext.getCurrentId());
       emp.setUpdateTime(LocalDateTime.now());
       emp.setPassword(newPassword);
        employeeMapper.UpdatePassword(emp);

    }

}
